
const jwt=require('jsonwebtoken');
const {
    TOKEN_KEY,
    WHITE_LIST
}=require('../config');

const {parse}=require('url');
module.exports=(options)=>{
    return async function(ctx,next){
        // console.log(ctx.request.url);
        let {pathname}=parse(ctx.request.url);
        let flag=WHITE_LIST.includes(pathname);
        // console.log(flag);
        if(!flag){//校验token
            let token=ctx.request.headers['authorization'];
            // console.log(token)
           if(!token){
            ctx.status=401;
            ctx.body={
                code:1002,
                msg:'token不尊在'
            }
           }else{
            let {exp}=jwt.verify(token,TOKEN_KEY);
            if(+new Date()>exp){
                ctx.status=401,
                ctx.body={
                    code:1002,msg:'token已失效'
                }
            }else{
                await next();
            }
           }
        }else{
            await next()
        }
    }
}